package com.xiaoran.service.connector.handler;

import com.xiaoran.common.data.RpcRequest;
import com.xiaoran.common.data.RpcResponse;
import com.xiaoran.common.utils.SpringBeanFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Rpc的服务端数据接收处理
 */
@Component
@ChannelHandler.Sharable
public class RpcRequestHandler extends SimpleChannelInboundHandler<RpcRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext,
                                RpcRequest rpcRequest) throws Exception {
        RpcResponse rpcResponse = new RpcResponse();

        String requestId = rpcRequest.getRequestId();
        String className = rpcRequest.getClassName();
        Object[] parameters = rpcRequest.getParameters();
        String methodName = rpcRequest.getMethodName();
        Class<?>[] parameterTypes = rpcRequest.getParameterTypes();

        try {
            Object targetClass = SpringBeanFactory.getBean(Class.forName(className));
            Method method = targetClass.getClass().getMethod(methodName, parameterTypes);
            Object result = method.invoke(targetClass, parameters);
            rpcResponse.setResult(result);
            rpcResponse.setRequestId(requestId);

        } catch (Throwable cause) {
            rpcResponse.setCause(cause);
        }
        channelHandlerContext.writeAndFlush(rpcResponse);
    }
}
